/*
 * Copyright 2003-2006 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

%include lua/lua_fnptr.i

%{
	void print_traceback(lua_State* L, const char* msg)
	{
		if (msg) printf(msg);
		lua_getfield(L, LUA_GLOBALSINDEX, "print"); // push print
		lua_pushvalue(L, -2);		// push error msg
		lua_call(L, 1, 0);			// call print(error msg)
		lua_pop(L, 1);			// pop the err msg
    }


	lua_State* _validate_callable(void* data, int index)
	{
		lua_State* callable = (lua_State*)data;
		
		if ( !lua_isfunction(callable, index) )
		{
			printf( "The python callback is not callable!\n" );
			return 0;
		}
		
		return callable;
	}
	
	
	typedef struct LuaFunctionData
	{
		lua_State* state;
	} LuaFunctionData;

	typedef LuaFunctionData* luaFunctionHandle;

	luaFunctionHandle storeLuaFunction(SWIGLUA_FN fn)
	{
		luaFunctionHandle id = calloc(1, sizeof(LuaFunctionData));
		id->state = fn.L;

		lua_pushlightuserdata(id->state, id);			// push lightuserdata element (the table key)
		SWIGLUA_FN_GET(fn);
		lua_settable(id->state, LUA_REGISTRYINDEX);		// enters the info into the registry table
		
		return id;
	}
	
	lua_State* getLuaFunctionState(luaFunctionHandle id)
	{
		return id->state;
	}

	void pushLuaFunction(luaFunctionHandle id)
	{
		lua_pushlightuserdata(id->state, id);				// push lightuserdata element (the table key)
		lua_gettable(id->state, LUA_REGISTRYINDEX);		// get the info from the registry table
	}

	void freeLuaFunction(luaFunctionHandle id)
	{
		lua_pushlightuserdata(id->state, id);				// push lightuserdata element (the table key)
		lua_pushnil(id->state);
		lua_settable(id->state, LUA_REGISTRYINDEX);		// enters the info into the registry table
		
		free( id );
	}
%}